package hypermediaresearch.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/*
 * VinhJune 2012
 */
import org.slim3.datastore.Datastore;
import org.slim3.util.BeanUtil;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.Transaction;

import hypermediaresearch.meta.PartnerMeta;
import hypermediaresearch.meta.ProjectMeta;
import hypermediaresearch.meta.ProjectPartnerMeta;
import hypermediaresearch.model.Partner;
import hypermediaresearch.model.Project;
import hypermediaresearch.model.ProjectPartner;


public class PartnerService {
    private PartnerMeta p = new PartnerMeta();
    private ProjectMeta prj = new ProjectMeta();
    private ProjectPartnerMeta pp = new ProjectPartnerMeta();
    
    public Partner addPartner(Map<String, Object> input){
        Partner partner = new Partner();
        
        BeanUtil.copy(input, partner);
        
        System.out.println(partner.getName());
        
        Transaction tx = Datastore.beginTransaction();
        Datastore.put(partner);
        tx.commit();
        
        return partner;
    }
    
    public List<Partner> getPartnerList(){
        return Datastore.query(p).sort(p.name.desc).asList();
    }
    
    public List<Project> getCoordinatedProjectList(Partner partner){
        return Datastore.query(prj)
                .filter(prj.coordinatorRef.equal(partner.getKey()))
                        .sort(prj.name.desc)
                        .asList();
    }
    
    
    public List<Project> getParticipatedProjectList(Partner partner){
        List<Project> participatedList = new ArrayList<Project>();
        for (ProjectPartner pp : partner.getProjectPartnerListRef().getModelList()) {
            participatedList.add(pp.getProjectRef().getModel());
        }
        return participatedList;
    }
    
    public Partner getPartnerByName(String input){
         return Datastore.query(p)
                 .filter(p.name.equal(input))
                 .asSingle();
     }
}
